package com.github.interview.handler;


import com.github.interview.http.BusinessException;
import com.github.interview.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author Stephen
 * @date 2020/6/15 15:19
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> notReadable(HttpMessageNotReadableException e) {
        log.error("参数解析失败", e);
        return Result.failed(HttpStatus.BAD_REQUEST);
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result<String> mediaTypeNotSupported(HttpMediaTypeNotSupportedException e) {
        log.error("不支持的media类型", e);
        return Result.failed(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    @ExceptionHandler(BusinessException.class)
    public Result<String> businessError(BusinessException ex) {
        log.error("业务异常", ex);
        return Result.failed(ex);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<String> internalError(Exception e) {
        log.error("服务器内部异常", e);
        return Result.failed(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
